import { createApp } from 'vue';
import App from './App.vue';
import router from './route/router';
import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css';
import axios from 'axios';
import moment from 'moment';
import zhCn from 'element-plus/es/locale/lang/zh-cn'



const app = createApp(App);
app.use(ElementPlus, {
    locale: zhCn,
})
app.use(router);

if (process.env.NODE_ENV == "development") {
    console.log('开发环境')
    //开发环境
    axios.defaults.baseURL = '/api';
} else if (process.env.NODE_ENV == "production") {
    //生产环境
    console.log('生产环境')
} else {
    //本地环境
}   


//拦截器，
axios.interceptors.request.use(function (config) {
    //携带token
    const token = localStorage.getItem("token")
    config.headers.Authorization = `Bearer ${token}`
    return config;
}, function (error) {
    return Promise.reject(error);
});

axios.interceptors.response.use(function (response) {
    console.log(response);
    const { authorization } = response.headers
    //这里是如果有新的token返回（说明这次发请求的没有过期），就重新设置
    //如果过期了，后端会发错误码，前端处理重定向登录
    authorization && localStorage.setItem("token", authorization)
    return response;
}, function (error) {
    if (error.response.status === 401) {
        localStorage.removeItem("token")
        router.push("/Login")
    }
    return Promise.reject(error);
});



app.config.globalProperties.$axios = axios;
app.config.globalProperties.$moment = moment;

app.mount('#app');
